const app = getApp()
const db = wx.cloud.database();
const _ = db.command;
Component({
  options: {
    addGlobalClass: true,
  },
  data: {
    openid: app.globalData.openid,
    userInfo: null,

    idols: [],
    idolsID: {},

    // 翻页加载
    page: 1,
    size: 10,

    canIUseGetUserProfile: false,
    starCount: 0,
    forksCount: 0,
    visitTotal: 0,
  },

  attached: function () {
    console.log("success88")
    // console.log(this.openid = await app.getOpenid())
    let that = this;
    wx.showLoading({
      title: '数据加载中',
      mask: true,
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    let i = 0;
    numDH();
    loadUser();

    function loadUser() {
      app.getOpenid(function (result) {
        that.loadIdol(true);
        that.setData({
          openid: result
        })
        app.getUserInfo1(function (result2) {
          that.setData({
            userInfo: result2
          })
        }, result)
        // app.getTaskCount(function (result3) {
        //   console.log(result3)
        //   that.setData({
        //     signNum: result3.signNum,
        //     signTime: result3.signTime,
        //     luckNum: result3.luckNum
        //   })
        // }, result)
      })
      // console.log('come out'+a)
    }
    function numDH() {
      if (i < 20) {
        setTimeout(function () {
          that.setData({
            starCount: i,
            forksCount: i,
            visitTotal: i
          })
          i++
          numDH();
        }, 20)
      } else {
        that.setData({
          // openid: this.openid,
          starCount: that.coutNum(3000),
          forksCount: that.coutNum(484),
          visitTotal: that.coutNum(24000)
        })
      }
    }
    wx.hideLoading()
  },

  methods: {

    // 翻页加载 偶像信息
    loadIdol: function (isNew) {
      console.log("取偶像-分页")
      // console.log(isNew)
      // 先取出集合记录总数wx.getStorageSync('openid')
      let that = this;
      db.collection('ad_user_idol').where({
        _openid: app.globalData.openid
      }).count({
        success: res2 => {
          // console.info(res2)
          const total1 = res2.total
          // 计算需分几次取
          // const batchTimes = Math.ceil(total / 100)
          let size = this.data.size,
            page = this.data.page,
            total = Math.ceil(total1 / size);
          if (isNew == true) {
            that.setData({
              page: 1
            })
            page = 1
          }
          if (page <= total) {
            console.log("total=" + total)
            // db.collection('ad_user_idol').aggregate()
            // .lookup({
            //   from: 'ad_idol',
            //   localField: 'idol_id',
            //   foreignField: '_id',
            //   as: 'idolList',
            // })
            // .end()
            // .then(res => {
            wx.cloud.callFunction({
              name: 'dbLookup',
              data: {
                db_name: 'ad_user_idol',
                lookup: {
                  from: 'ad_idol',
                  localField: 'idol_id',
                  foreignField: '_id',
                  as: 'idol'
                },
                match: {
                  hasdel: 0
                },
                sort: {
                  create_time: -1
                },
                skip: ((page - 1) * size),
                limit: size
              }
            }).then(kkk => {
              console.log("kkk page=" + page)
              console.log(kkk)
              page++
              let list = kkk.result.list,
                length = list.length,
                idols = that.data.idols,
                idolsID = that.data.idolsID;
              if (isNew == true) {
                idols = []
                idolsID = {}
              }
              if (length > 0) {
                for (let i = 0; i < length; i++) {
                  if (!idolsID['idol_' + list[i].idol_id]) {
                    // 时间转换
                    // list[i].date = that.timeRend(list[i].create_time)
                    var item = list[i].idol[0];
                    item.hasvote = list[i].hasvote;
                    idols.push(item)
                    idolsID['idol_' + list[i].idol_id] = 1
                  }
                }
              }
              // console.log("kkk page=" + page)
              that.setData({
                idols: idols,
                idolsID: idolsID,
                page: page
              })
            })
              .catch(err => console.error(err))
          }
        }
      })
    },
    //打开详情
    idolTap: function (e) {
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/idol/detail?id=' + id
      })
    },
    getUserProfile(e) {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
      // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          var user = res.userInfo
          console.log('uinfo=');
          console.log(user);
          if (user) {
            console.log('读库=' + wx.getStorageSync('openid'));
            db.collection('userinfo').where({
              _openid: wx.getStorageSync('openid')
            }).get({
              success: res => {
                if (res.data.length > 0) {
                  //1.存用户信息到本地存储
                  console.log('ku have')
                  console.log(res.data[0])
                  wx.setStorageSync('userInfo', res.data[0])
                  //2.存用户信息到全局变量
                  app.globalData.userInfo = res.data[0]
                  wx.setStorageSync('isLogin', true);
                  wx.navigateBack({
                    delta: 1
                  })
                } else {
                  // 新用户 
                  console.log('no have')
                  //     "level":1,
                  //     "point":40,
                  // "income":40,
                  // "spend":40,
                  // "create_time":1619798400,
                  // "update_time":1619798400
                  // inviter 邀请者
                  user.level = 1;
                  user.point = 28;
                  user.income = 28;
                  user.spend = 0;
                  user.create_time = app.nowTimeStamp()
                  user.update_time = app.nowTimeStamp()
                  console.log(user)
                  wx.setStorageSync('userInfo', user)
                  //2.存用户信息到全局变量
                  app.globalData.userInfo = user
                  wx.setStorageSync('isLogin', true);
                  //授权成功后，跳转进入小程序首页
                  db.collection('userinfo').add({
                    // data 字段表示需新增的 JSON 数据
                    data: user
                  }).then(res => {
                    wx.setStorageSync('isLogin', true);
                    console.log(res)
                    wx.navigateBack({
                      delta: 1
                    })
                  })
                }
              },
              fail: err => {
                wx.setStorageSync('isLogin', false);
                console.log('[数据库] [查询记录] 失败：')
              }
            })
          }
        }
      })
    },
    getUserInfo1: function (openid) {
      let that = this;
      db.collection('userinfo').where({
        _openid: openid
      }).get().then(res => {
        if (res.data.length > 0) {
          console.log("cha ku =")
          var user = res.data[0]
          console.log(user)
          wx.setStorageSync('userInfo', user)
          //2.存用户信息到全局变量
          app.globalData.userInfo = user
          wx.setStorageSync('isLogin', true);

          that.setData({
            userInfo: user
          })
          //更新数据并登录
          // userInfo.update_time = this.getDatetime(new Date())
          // this.db.collection('user').where({
          //   _openid: openid
          // }).update({
          //   data: userInfo,
          //   success: res1 => {
          //     for (let x in userInfo) {
          //       res.data[0][x] = userInfo[x]
          //     }

          //     app.globalData.userInfo = res.data[0]
          //     if (typeof success == 'function') success(res.data[0])
          //     return
          //   },
          //   fail: err => {
          //     icon: 'none',
          //       console.error('用户更新失败：', err)
          //   }
          // })
        } else {
          // userInfo.create_time = this.getDatetime(new Date())
          // userInfo.update_time = this.getDatetime(new Date())
          // this.db.collection('user').add({
          //   data: userInfo
          // }).then(res => {
          //   userInfo._openid = openid
          //   userInfo._id = res._id
          //   app.globalData.userInfo = userInfo
          //   if (typeof success == 'function') success(userInfo)
          //   return
          // })
        }
      })
    },
    // 格式化数字
    coutNum(e) {
      if (e > 1000 && e < 10000) {
        e = (e / 1000).toFixed(1) + 'k'
      }
      if (e > 10000) {
        e = (e / 10000).toFixed(1) + 'W'
      }
      return e
    },
  }
})